package org.jflame.uid.segment.dao.impl;

import org.jflame.uid.segment.dao.IDAllocDao;
import org.jflame.uid.segment.dao.IDAllocMapper;
import org.jflame.uid.segment.model.LeafAlloc;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * 基于mybatis实现IDAllocDao
 */
public class IDAllocMybaisImpl implements IDAllocDao {

    private SqlSessionFactory sqlSessionFactory;

    public IDAllocMybaisImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public List<LeafAlloc> getAllLeafAllocs() {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        try {
            // return sqlSession.selectList("org.jflame.uid.segment.dao.IDAllocMapper.getAllLeafAllocs");
            IDAllocMapper mapper = sqlSession.getMapper(IDAllocMapper.class);
            return mapper.getAllLeafAllocs();
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public LeafAlloc updateMaxIdAndGetLeafAlloc(String tag) {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        try {
            // sqlSession.update("org.jflame.uid.segment.dao.IDAllocMapper.updateMaxId", tag);
            // LeafAlloc result = sqlSession.selectOne("org.jflame.uid.segment.dao.IDAllocMapper.getLeafAlloc", tag);
            IDAllocMapper mapper = sqlSession.getMapper(IDAllocMapper.class);
            mapper.updateMaxId(tag);
            LeafAlloc result = mapper.getLeafAlloc(tag);
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public LeafAlloc updateMaxIdByCustomStepAndGetLeafAlloc(LeafAlloc leafAlloc) {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        try {
            IDAllocMapper mapper = sqlSession.getMapper(IDAllocMapper.class);
            mapper.updateMaxIdByCustomStep(leafAlloc);
            LeafAlloc result = mapper.getLeafAlloc(leafAlloc.getKey());
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public List<String> getAllTags() {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        try {
            // return sqlSession.selectList("org.jflame.uid.segment.dao.IDAllocMapper.getAllTags");
            IDAllocMapper mapper = sqlSession.getMapper(IDAllocMapper.class);
            return mapper.getAllTags();
        } finally {
            sqlSession.close();
        }
    }
}
